package com.joelaws.prototype.server;

import java.util.Map;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.rpc.Manage;
import com.joelaws.prototype.client.util.Create;
import com.joelaws.prototype.server.blackberry.RestletApp;
import com.joelaws.prototype.server.dao.DAOFactory;

public class ManageImpl extends RemoteServiceServlet implements Manage {

	private static final long serialVersionUID = 1L;

	static {
		RestletApp.activate();
	}

	public User login(String email, String password) throws Exception {
		System.out.println("login start");
		try {
			return DAOFactory.getUserDAO().getUser(email.trim(), password.trim());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			System.out.println("login end");
		}
	}

	public User register(String email, String firstName, String lastName, String password) throws Exception {
		System.out.println("register start");
		try {
			User user = new User(firstName.trim(), lastName.trim(), email.trim(), password.trim());
			DAOFactory.getUserDAO().storeUser(user);
			return user;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			System.out.println("register end");
		}
	}

	public void updateUser(User user) throws Exception {
		System.out.println("updateUser start");
		try {
			DAOFactory.getUserDAO().storeUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			System.out.println("updateUser end");
		}
	}

	public Map<Long, User> getUsers(long[] userIDs) throws Exception {
		System.out.println("getUsers start");
		try {
			Map<Long, User> users = Create.newMap();
			for (long userID : userIDs) {
				User user = DAOFactory.getUserDAO().getUser(userID);
				if (user != null)
					users.put(userID, user);
			}
			return users;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			System.out.println("getUsers end");
		}
	}

	public User getUser(long userID) throws Exception {
		System.out.println("getUser start");
		try {
			return DAOFactory.getUserDAO().getUser(userID);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			System.out.println("getUser end");
		}
	}
}
